﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CSharpTaskLongRunningAndCrossControl
{
    public partial class FrmTask : Form
    {
        public FrmTask()
        {
            InitializeComponent();
        }

        //启动长时间运行的任务
        private void btnLongInRunning_Click(object sender, EventArgs e)
        {
            Task task = new Task(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine($"Task子线程Id={Thread.CurrentThread.ManagedThreadId}");
            },TaskCreationOptions.LongRunning); //添加这个枚举，告诉系统，这个任务可能会长时间运行
            task.Start();

            Console.WriteLine("主线程开始运行！Time=" +DateTime.Now.ToLongTimeString());
        }

        //跨线程更新数据
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Task task = new Task(() =>
            {
                this.lblInfo.Text = "来自Task的数据更新：我们正在学习Task多线程";
            });
            //task.Start();  //这样直接使用会直接报错
            task.Start(TaskScheduler.FromCurrentSynchronizationContext()); //其实这个本意和Thread一样，就是使用委托同步到主线程
        }

        //耗时任务
        private void btn2_Click(object sender, EventArgs e)
        {
            Task task = new Task(() =>
            {
                Thread.Sleep(5000); //模拟耗时的任务.......
                this.lblInfo.Text = "来自Task的数据更新：我们正在学习Task多线程";
            });
            task.Start(TaskScheduler.FromCurrentSynchronizationContext()); 
        }

        //耗时任务UI卡顿问题解决
        private void btn3_Click(object sender, EventArgs e)
        {
            this.lblInfo.Text = "数据更新中，请耐心等待";
            Task task = Task.Run(() =>
            {
                Thread.Sleep(5000); //模拟耗时的任务.....
                //this.lblInfo.Text = "来自Task的数据更新：我们正在学习Task多线程";
            });

            //更新UI的任务做一个延续
            task.ContinueWith(t =>
            {
                this.lblInfo.Text = "来自Task的数据更新：我们正在学习Task多线程";
            }, TaskScheduler.FromCurrentSynchronizationContext());
            
        }
    }
}
